﻿using System;
using System.Collections.Generic;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using Microsoft.Practices.Unity;
using SpectrumAnalyser.Common.Hosting;
using SpectrumAnalyser.Common.ServiceHeaders;
using SpectrumAnalyser.ModelObjects.Enum;
using SpectrumAnalyser.Services.Common.Bevaviors;

namespace SpectrumAnalyser.ServiceClientProxy
{
    /// <summary>
    /// Register specified services on client application for specified instanceName. Add behaviors for each service endpoint.
    /// </summary>
    public class ClientBootstrapperBase
    {
        private readonly IUnityContainer _unityContainer;

        protected readonly string _instanceName;

        public ClientBootstrapperBase(IUnityContainer container, string instanceName)
        {
            this._unityContainer = container;
            this._instanceName = instanceName;
        }

        public void RegisterServices(IList<Type> types)
        {
            foreach (var type in types)
            {
                var clientGenerator = new CustomDebugServiceClientGenerator(type);
                var clientType = clientGenerator.CreateProxyType();

                var endpointUri = WcfHelper.GetEndpointUri(UriScheme.Http, type);
                var enpointAddress =
                    new EndpointAddress(endpointUri);
                Binding binding = WcfHelper.GetBinding(UriScheme.Http);

                var injection = new InjectionConstructor(GetEndpointBehaviors(), binding, enpointAddress);
                this._unityContainer.RegisterType(type, clientType, injection);
            }
        }

        protected virtual IList<IEndpointBehavior> GetEndpointBehaviors()
        {
            var instanceNameEndpointBehavior =
                new InstanceNameEndpointBehavior(new InstanceNameHeader {InstanceName = this._instanceName});

            return new IEndpointBehavior[] {instanceNameEndpointBehavior};
        }
    }
}